package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.dao.BspsInspectRegisterInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsInspectTaskDetailMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsInspectRegisterInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsInspectTaskDetailMapperImpl;
import cc.rengu.igas.bsps.common.entity.InspectRegisterInfo;
import cc.rengu.igas.bsps.common.entity.InspectTaskDetail;
import cc.rengu.igas.bsps.common.enums.InspectStatusEnum;
import cc.rengu.igas.bsps.common.enums.InspectTypeEnum;
import cc.rengu.igas.bsps.common.enums.RecordStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.BankManagerService;
import cc.rengu.igas.bsps.facade.bean.InspectCollectInfoBean;
import cc.rengu.igas.bsps.facade.request.MchntInspectInfoCollectRequest;
import cc.rengu.igas.bsps.facade.response.MchntInspectInfoCollectResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020.04.08
 */
public class MchntInspectInfoCollectService extends BankManagerService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntInspectInfoCollectRequest mchntInspectInfoCollectRequest = new MchntInspectInfoCollectRequest();
        ConvertUtil.convertOutput(mchntInspectInfoCollectRequest);
        return mchntInspectInfoCollectRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntInspectInfoCollectRequest mchntInspectInfoCollectRequest = (MchntInspectInfoCollectRequest) request;
        /*获取请求参数判断必填性*/
        String instId = mchntInspectInfoCollectRequest.getHeader().getInstId();
        String userId = mchntInspectInfoCollectRequest.getUserId();
        String inspectTaskNo = mchntInspectInfoCollectRequest.getInspectTaskNo();
        String mchntNo = mchntInspectInfoCollectRequest.getMchntNo();
        String inspectType = mchntInspectInfoCollectRequest.getInspectType();
        List<InspectCollectInfoBean> inspectCollectInfoList = mchntInspectInfoCollectRequest.getInspectCollectInfoList();
        boolean checkInspectInfoFlag = checkInspectCollectInfoVlae(inspectCollectInfoList);
        if (StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(inspectTaskNo) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(inspectType) || checkInspectInfoFlag) {
            rglog.error("商户巡检信息采集交易必填行校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*1-登记自助巡检图片信息 2-更新商户巡检任务详情信息*/
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        int iReturnCode;
        /*1-登记巡检图片*/
        BspsInspectRegisterInfoMapper bspsInspectRegisterInfoMapper = new BspsInspectRegisterInfoMapperImpl();
        for (InspectCollectInfoBean inspectCollectInfo : inspectCollectInfoList) {
            InspectRegisterInfo inspectRegisterInfo = new InspectRegisterInfo();
            /*法人行号赋值*/
            inspectRegisterInfo.setInstId(instId);
            /*巡检任务编号赋值*/
            inspectRegisterInfo.setInspectTaskNo(inspectTaskNo);
            /*商户号赋值*/
            inspectRegisterInfo.setMchntNo(mchntNo);
            /*采集信息标识*/
            inspectRegisterInfo.setCollectId(inspectCollectInfo.getCollectId());
            /*采集信息类型赋值*/
            inspectRegisterInfo.setCollectType(inspectCollectInfo.getCollectType());
            /*采集信息描述*/
            inspectRegisterInfo.setCollectDesc(inspectCollectInfo.getCollectDesc());
            /*采集信息赋值*/
            if ("2".equals(inspectCollectInfo.getCollectType())) {
                inspectRegisterInfo.setCollectValue(new String(Base64.decodeBase64(inspectCollectInfo.getCollectValue())));
            } else {
                inspectRegisterInfo.setCollectValue(inspectCollectInfo.getCollectValue());
            }
            /*记录状态：默认正式*/
            inspectRegisterInfo.setRecordStatus(RecordStatusEnum.FORMAL.getStatus().substring(1));
            /*创建人信息赋值*/
            inspectRegisterInfo.setOprId(userId);
            /*创建时间赋值*/
            inspectRegisterInfo.setCreateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
            /*非业务主键赋值*/
            inspectRegisterInfo.setId(RandomUtil.getUUID());
            iReturnCode = bspsInspectRegisterInfoMapper.insertInspectRegisterInfo(inspectRegisterInfo);
            if (0 != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("新增商户巡检采集信息失败,iReturnCode:<{}>,类型:<{}>,描述信息:<{}>", iReturnCode, inspectCollectInfo.getCollectType(), inspectCollectInfo.getCollectDesc());
                throw new BizException(RespCodeEnum.INSERT_INSPECT_TASK_REGISTER_ERROR.getRespCode(), RespCodeEnum.INSERT_INSPECT_TASK_REGISTER_ERROR.getRespDesc());
            }
        }
        /*2-更新商户巡检任务详情信息*/
        BspsInspectTaskDetailMapper bspsInspectTaskDetailMapper = new BspsInspectTaskDetailMapperImpl();
        InspectTaskDetail inspectTaskDetail = new InspectTaskDetail();
        /*法人行号赋值*/
        inspectTaskDetail.setInstId(instId);
        /*商户号赋值*/
        inspectTaskDetail.setMchntNo(mchntNo);
        /*巡检任务编号赋值*/
        inspectTaskDetail.setInspectTaskNo(inspectTaskNo);
        /*巡检任务状态赋值*/
        if (!InspectTypeEnum.ONLINE_INSPECT.getInspectType().equals(inspectType)) {
            /*线下巡检及电话巡检*/
            inspectTaskDetail.setInspectStatus(InspectStatusEnum.CHECK_STATUS.getStatusCode());
        } else {
            /*线上巡检*/
            inspectTaskDetail.setInspectStatus(InspectStatusEnum.UNCHECK_STATUS.getStatusCode());
        }
        /*巡检时间赋值*/
        inspectTaskDetail.setInspectTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
        /*最后操作人赋值*/
        inspectTaskDetail.setLastOprId(userId);
        /*最后操作时间赋值*/
        inspectTaskDetail.setLastUpdateTime(DateUtil.getCurrentDateTime(BspsAppParamConstant.yyyy_MM_dd_HHmmssSSS));
        iReturnCode = bspsInspectTaskDetailMapper.updateBspsInspectTaskDetailByMchntNoAndTaskNo(inspectTaskDetail);
        if (0 != iReturnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("更新商户巡检任务信息失败,iReturnCode:<{}>,mchntNo:<{},inspectTaskNo:<{}>", iReturnCode, mchntNo, inspectTaskNo);
            throw new BizException(RespCodeEnum.UPDATE_INSPECT_TASK_DETAIL_ERROR.getRespCode(), RespCodeEnum.UPDATE_INSPECT_TASK_DETAIL_ERROR.getRespDesc());
        }
        dbsUtil.dbsEndTransaction(true);
        /* 拼装响应结果 */
        MchntInspectInfoCollectResponse mchntInspectInfoCollectResponse = new MchntInspectInfoCollectResponse();
        BizResponse<MchntInspectInfoCollectResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntInspectInfoCollectResponse);
        return bizResponse;
    }

    /*校验巡检信息必填字段
     * inspectImageInfoList 巡检资料信息列表
     * return 必填信息是否为空标识
     * */
    private boolean checkInspectCollectInfoVlae(List<InspectCollectInfoBean> inspectCollectInfoList) {
        boolean imageListFlag = false;
        try {
            if (!CollectionUtils.isEmpty(inspectCollectInfoList)) {
                for (InspectCollectInfoBean inspectCollectInfo : inspectCollectInfoList) {
                    /*影像信息属性名称，属性首字母，获取属性方法，属性值*/
                    rglog.info("巡检内容标识Id:" + inspectCollectInfo.getCollectId());
                    String firstLetter;
                    String fieldName;
                    String fieldValue;
                    Method method;
                    Field[] fields = inspectCollectInfo.getClass().getDeclaredFields();
                    for (int i = 0, fieldsLength = fields.length; i < fieldsLength; i++) {
                        Field imageFiled = fields[i];
                        fieldName = imageFiled.getName();
                        rglog.info("巡检内容校验字段信息：" + fieldName);
                        //经纬度不校验
                        if ("collectImageLng".equals(fieldName) || "collectImageLat".equals(fieldName) || "id".equals(fieldName)) {
                            continue;
                        }
                        firstLetter = fieldName.substring(0, 1).toUpperCase();
                        String getterField = "get" + firstLetter + fieldName.substring(1);
                        method = inspectCollectInfo.getClass().getMethod(getterField);
                        fieldValue = method.invoke(inspectCollectInfo).toString();
                        if (StringUtil.isEmptyOrNull(fieldValue)) {
                            rglog.info("巡检采集信息必填字段校验失败！" + fieldName);
                            imageListFlag = true;
                            break;
                        }

                    }
                }
            } else {
                imageListFlag = true;
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("影像信息必填字段校验失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        return imageListFlag;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntInspectInfoCollectResponse mchntInspectInfoCollectResponse = (MchntInspectInfoCollectResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntInspectInfoCollectResponse);
    }
}
